package com.kehutong.payfees.app;

import java.math.BigDecimal;

import com.kehutong.common.DoveClient;
import com.kehutong.common.math.CalculatorUtils;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.record.Account;
import com.kehutong.payfees.entity.record.ChargeRecord;
import com.kehutong.payfees.enums.WaterSource;
import com.kehutong.payfees.service.ChargeRecordServiceImpl;
import com.kehutong.payfees.service.record.AccoutServiceImpl;
import com.kehutong.payfees.syn.CallBackReturn;
import com.kehutong.payfees.syn.Locks;
import com.kehutong.payfees.util.BasicClient;
import com.kehutong.payfees.util.ContactClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import com.kehutong.payfees.entity.record.AccWater;

import javax.servlet.http.HttpServletRequest;

/**
 * Author:  peter
 * Date:    2020/7/8
 * Function:业主端-缴费模块 房屋
 */
@MvcAction
@ReqMapping("/kht-bin/charge/client")
public class ChargeHouseAction {

    @Inject
    private AccoutServiceImpl accoutService;
//    @Inject
//    private PaymentService webChatPayService;
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    @Inject
    private BasicClient basicClient;
    @Inject
    private ContactClient contactClient;
    @Inject
    private ChargeRecordServiceImpl chargeRecordService;


    /**
     * @param houseNo 充值目标房屋
     * @param amt     充值金额
     */
    @ReqMapping("/charge_house")
    public Object chargeHouse(Token token, HttpServletRequest req, String houseNo, BigDecimal amt) throws Exception {

        if (Objects.isEmpty(token.getUuid())) {
            return Result.unlogin();
        }
        if (amt == null) {
            return Result.error(0, "请输入充值金额");
        }
        if (CalculatorUtils.getDecimalPlace(amt) > 2) {
            return Result.error(0, "金额小数位最多支持2位");
        }
        if (amt.compareTo(BigDecimal.ZERO) < 0) {
            return Result.error(0, "金额必须为正数");
        }

        if (Objects.isEmpty(houseNo)) {
            return Result.error(0, "请选择要充值的房屋");
        }

//        WebChat c = Pool.get(WebChat.class, contactId);
//        if (Objects.isNull(c)) {
//            return Result.error(0, "不存在的外部联系人");
//        }

        JSONObject house = basicClient.getHouseById(token, houseNo);
        if (Objects.isNull(house)) {
            return Result.error(0, "不存在的房屋");
        }

        CallBackReturn<JSONObject> called = ()-> {
            ChargeRecord cr = Pool.newInstance(ChargeRecord.class);
            cr.setCommunityNo(house.getString("communityNo"));
            cr.setCommunityName(house.getString("communityName"));
            cr.setHouseNo(houseNo);
            chargeRecordService.setDepartmentNo(cr, token.getCompanyNo());
//            cr.setMbrCode(c.getId());
//            cr.setMbrName(c.getNickName());
//            cr.setMobile(c.getMobile());
//            cr.setAvatar(c.getAvatar());
//            cr.setOpenid(c.getOpenId());
            cr.setAmt(amt);
            cr.setTradeType("JSAPI");
            cr.setBizType(WaterSource.CHONGZHI);

            return chargeRecordService.createUnifiedOrderByChargeRecord(token, req, cr, "物业费预存", cr.getId(),"wxpay_web");
        };

        return Locks.exeSyn(token.getUuid(), called);
    }

    /**
     * 获取住户的房屋下拉列表
     */
    @ReqMapping("/house/list")
    public Object listHouse(Token token, JSONObject req) throws Exception {
        JSONObject result = doveClient.post("/basic/house/service/list", http->{
            JSONObject body = new JSONObject();
            body.put("ownerNo", token.getUuid());

            http.addHeader("companyNo", token.getCompanyNo());
            http.setBody(body.toString());
        });

        JSONArray data = result.getJSONArray("data");
        return Result.success(data);
    }

    /**
     * 房屋详情
     */
    @ReqMapping("/house/get")
    public Object getHouse(Token token, JSONObject req) throws Exception {
        JSONObject data = basicClient.getHouseById(token, req.getString("id"));
        return Result.success(data);
    }

    /**
     * 房屋收支记录流水列表
     */
    @ReqMapping("/house/accwater/page")
    public Object pageHouseAccountWater(Token token, JSONObject req) throws Exception {

        Account account = accoutService.getHouseAccount(req.getString("houseNo"));

        FindPage<AccWater> find = jdbcSession.findPage(AccWater.class)
                .eq("accNo", account.getId())
                // 时间倒序
                .order("createTime", "DESC")
                .order("id", "DESC")
                .page(req);

        // TODO 找到一条未删除的用户-房屋绑定记录
//        CustomerHouse ch = jdbcSession.findOne(CustomerHouse.class)
//                .eq("houseId", req.getString("houseNo"))
//                .eq("contactId", session.getUserId())
//                .eq("deleted", false)
//                .exe();
//
//        if (ch == null) {
//            return Result.error(0, "您未申请绑定该房屋");
//        }
//        // 非业主 查看绑定后产生的记录
//        if (!CustomerType.OWNER.equals(ch.getUserType())) {
//            find.maxEq("createTime", ch.getCreateTime());
//        }

        Page<AccWater> page = find
                .exe();

        return Result.success(page);
    }

    /**
     * 房屋账户详情
     */
    @ReqMapping("/house/account/get")
    public Object getHouseAccount(JSONObject req) throws Exception {
       return accoutService.getHouseAccount(req.getString("houseNo"));
    }

    /**
     * 房屋账户自动扣款设置
     */
    @ReqMapping("/house/auto_advance/update")
    public Object updateHouseEnableAutoAdvance(Token token, JSONObject req) throws Exception {
        JSONObject data = basicClient.getHouseById(token, req.getString("id"));
        if (Objects.isNull(data)) {
            return Result.error(0, "不存在的房屋");
        }
        if (!Objects.equal(data.getString("ownerNo"), token.getUuid())) {
            return Result.error(0, "非该房屋业主");
        }

        //TODO 自动扣款开关未修改
//        house.setEnableAutoAdvance(req.getBoolean("enableAutoAdvance"));
//        jdbcSession.updateById(data);

        return Result.success();
    }

}
